<?php

/*
 * Snippet 2 from
 * http://www.php.net/manual/en/language.types.float.php
 */


/*
 * Create an instance of IndentedTextWriter to hold the generated code
 */

$writer = new IndentedTextWriter();

/*
 * Create an instance of the code generator options class
 */

$options = new CodeGeneratorOptions();

/*
 * Set the bracing style:
 */

$options->set_BracingStyle(BracingStyle::KR);

/*
 * both $writer and $options will be arguments to one of
 * the PHPCodeProvider code generating methods.
 * Create an instance of the PHP code provider class
 */

$provider = new PHPCodeProvider();

/*
 * Start creating the code tree.
 */

$defaultNamespace = new CodeNamespace();

/*
 * create expressions to be used in the statements
 */

$a_ref = new VariableReferenceExpression('a');
$b_ref = new VariableReferenceExpression('b');

$a_minus_b_ref = new BinaryOperatorExpression(BinaryOperator::SUBTRACT);
$a_minus_b_ref->Left = $a_ref;
$a_minus_b_ref->Right = $b_ref;

$epsilon_ref = new VariableReferenceExpression('epsilon');

$abs_ref = new FunctionReferenceExpression('abs');


/*
 * Start adding statements to the namespace.
 */

$assign_statement_1 = new AssignStatement(
    $a_ref, new PrimitiveExpression(1.23456789));

$assign_statement_2 = new AssignStatement(
    $b_ref, new PrimitiveExpression(1.23456780));

$assign_statement_3 = new AssignStatement(
    $epsilon_ref, new PrimitiveExpression(0.00001));
$assign_statement_3->BlankLinesAfter = 1;

$condition_expression = new BinaryOperatorExpression(BinaryOperator::LESS_THAN);
$condition_expression->Left = new FunctionInvokeExpression($abs_ref);
$condition_expression->Left->Parameters->add($a_minus_b_ref);
$condition_expression->Right = $epsilon_ref;

$if_statement = new IfElseStatement($condition_expression);
$if_statement->TrueStatements->add(new EchoStatement());
$if_statement->TrueStatements[0]->OutputParameters->add(
    new PrimitiveExpression('true'));
/*
 * Add the statements to the default namespace
 */

$defaultNamespace->Statements->add($assign_statement_1);
$defaultNamespace->Statements->add($assign_statement_2);
$defaultNamespace->Statements->add($assign_statement_3);
$defaultNamespace->Statements->add($if_statement);

/*
 * Generate the code
 */

$provider->generateCodeFromNamespace($defaultNamespace, $writer, $options);

/*
 * Print the generated code
 */

echo 
    '<pre>' . str_replace(
        '<br />', '', highlight_string($writer->get_String(), true)) . 
    '<pre/>';

/*
 * The output should be:
 * 
 * $a = 1.23456789;
 * $b = 1.2345678;
 * $epsilon = 1.0E-5;
 *
 * if(abs($a - $b) < $epsilon){
 *    echo 'true';
 * }
 *  
 */


?>
